module SessionHelpers
  extend Grape::API::Helpers

  def current_user
    return @current_user if @current_user
    user_id, authenticatable_salt = request.session['_current_user']
    user = User.where(id: user_id).first
    @current_user = user if user && user.encrypted_password.end_with?(authenticatable_salt)
  end

  def authenticate_user!
    error!('Forbidden', 403) unless current_user
  end

  def login
    return error!('Already signed in', 409) if request.session['_current_user']
    user_params = params[:user]
    user = User.where(email: user_params[:email]).first
    error!('Wrong credential', 403) unless user && user.password_valid?(user_params[:password])
    request.session.clear
    request.session['_current_user'] = [user.id, user.authenticatable_salt]
    {ok: true}
  end

  def logout
    request.session.clear
    {ok: true}
  end
end